package main;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

//Responsible for saving and retrieving the last downloaded rates
//at the application's record store.
//The first time the application needs the rates,
//some default values are loaded.
public class StorageHandler
{
    public static final String recordStoreName="RatesStore";
    
    public static void loadRates()
    {
        String[] stores=RecordStore.listRecordStores();
        if (stores==null)
        {
            try
            {
                RecordStore store=RecordStore.openRecordStore(recordStoreName, true);
                
                String[] defaultRates=new String[]{
                    "1.0",
                    "1.4306",
                    "0.8828",
                    "114.8025",
                    "1.4023",
                    "1.2106",
                    "1.7658",
                    "64.2576"
                };
                String rateValue = "";
                byte[] bytes = null;
                for (int i=0;i<defaultRates.length;i++)
                {
                    rateValue = defaultRates[i];
                    bytes = rateValue.getBytes();
                    store.addRecord(bytes,0,bytes.length);
                }
                store.closeRecordStore();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
        
        try
        {
            RecordStore store=RecordStore.openRecordStore(recordStoreName, true);
            RecordEnumeration re = store.enumerateRecords(null, null, false);
            float[] rates=new float[store.getNumRecords()];
            for (int i=0;i<store.getNumRecords();i++)
            {
                rates[store.getNumRecords()-1-i]=Float.parseFloat(new String(re.nextRecord()));
            }
            DataHandler.updateCurrencyData(rates,false);
        }
        catch (Exception ex)
        {
            
        }
    }
    
    
    public static void storeRates(float[] rates)
    {
        try
        {
            RecordStore store=RecordStore.openRecordStore(recordStoreName, true);
            byte[] dataToSave=null;
            for (int i=0;i<store.getNumRecords();i++)
            {
                dataToSave=String.valueOf(rates[i]).getBytes();
                store.setRecord(i+1, dataToSave, 0, dataToSave.length);
            }
            DataHandler.updateCurrencyData(rates,false);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}